package com.weex.app.module.tool;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

public class ImageUtils {

    public static String bitmapToString(Bitmap bitmap) {
        try {
            return bitmap != null ? Base64.encodeToString(Bitmap2Bytes(bitmap),
                    Base64.DEFAULT) : "";
        } catch (Exception e) {
            return "";
        }
    }

    public static Bitmap stringToBitmap(String base64) {
        try {
            return Bytes2Bimap(Base64.decode(base64, Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }
}
